<template>
  <div>
    <el-container>
      <el-aside width="50vw"></el-aside>
      <el-container>
        <el-header>商品管理系统</el-header>
        <el-main>
          <h1>注册</h1>
          <el-form
            :model="ruleForm"
            status-icon
            :rules="rules"
            ref="ruleForm"
            label-width="100px"
            class="demo-ruleForm form"
          >
            <el-form-item prop="email">
              <el-input
                v-model="ruleForm.email"
                placeholder="请输入用户名"
              ></el-input>
            </el-form-item>
            <el-form-item prop="pass">
              <el-input
                type="password"
                v-model="ruleForm.pass"
                autocomplete="off"
                placeholder="请输入密码"
              ></el-input>
            </el-form-item>
            <el-form-item prop="checkPass">
              <el-input
                type="password"
                v-model="ruleForm.checkPass"
                autocomplete="off"
                placeholder="请再次输入密码"
              ></el-input>
            </el-form-item>
            <el-form-item prop="code">
              <div class="sendCode">
                <el-input
                  type="text"
                  v-model="ruleForm.code"
                  autocomplete="off"
                  class="code"
                  placeholder="请输入验证码"
                ></el-input>
                <el-button
                  :disabled="bool"
                  type="primary"
                  @click="sendCode"
                  class="btnCode"
                  >{{ btnText }}</el-button
                >
              </div>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitForm('ruleForm')"
                >提交</el-button
              >
              <el-button @click="resetForm('ruleForm')">重置</el-button>
            </el-form-item>
          </el-form>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script>
export default {
  data() {
    var validatePass = (rule, value, callback) => {
      let reg = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{6,20}$/;
      if (value === "") {
        callback(new Error("请输入密码"));
      } else if (!reg.test(value)) {
        callback(
          new Error(
            "请输入6-20个字符，至少一个大写字母，一个小写字母，一个数字"
          )
        );
      } else {
        if (this.ruleForm.checkPass !== "") {
          this.$refs.ruleForm.validateField("checkPass");
        }
        callback();
      }
    };
    var validateEmail = (rule, value, callback) => {
      let reg = /^\w+@[a-zA-Z0-9]+((\.[a-z0-9A-Z]{1,})+)$/;
      if (value === "") {
        callback(new Error("请输入邮箱地址"));
      } else if (!reg.test(value)) {
        callback(new Error("邮箱格式错误"));
      } else {
        if (this.ruleForm.checkPass !== "") {
          this.$refs.ruleForm.validateField("checkPass");
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.ruleForm.pass) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      ruleForm: {
        pass: "",
        checkPass: "",
        email: "",
        code: "",
      },
      rules: {
        email: [{ required: true, validator: validateEmail, trigger: "blur" }],
        pass: [{ required: true, validator: validatePass, trigger: "blur" }],
        checkPass: [
          { required: true, validator: validatePass2, trigger: "blur" },
        ],
      },
      emailCode: "",
      bool: false,
      btnText: "发送验证码",
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.ruleForm.code !== this.emailCode) {
            this.$message({
              showClose: true,
              message: "验证码错误",
              type: "error",
            });
          } else {
            this.axios({
              method: "post",
              url: "http://localhost:3000/register",
              data: {
                username: this.ruleForm.email,
                password: this.ruleForm.pass,
              },
            }).then(res =>{
              console.log(res);
              this.$router.push('/login');
            });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    sendCode() {
      if (!this.bool) {
        this.bool = true;
        this.btnText = "5s";
        let countDown = 5;
        let timeout = window.setInterval(() => {
          countDown--;
          this.btnText = `${countDown}s`;
          if (!countDown) {
            window.clearInterval(timeout);
            this.bool = false;
            this.btnText = "发送验证码";
          }
        }, 1000);
      }

      this.axios({
        method: "post",
        url: "http://localhost:3000/emailcode",
        data: {
          email: this.ruleForm.email,
        },
      })
        .then((res) => {
          // console.log(res);
          this.emailCode = res.data.emailCode;
        })
        .catch((err) => {
          console.log(err);
        });
    },
  },
};
</script>

<style lang="less" scoped>
.el-header,
.el-footer {
  color: #728ded;
  // text-align: center;
  line-height: 60px;
  font-size: 20px;
}

.el-aside {
  background: url("../assets/register.jpg") no-repeat -330px -200px;
  color: #333;
  text-align: center;
  height: 100vh;
}

.el-main {
  color: #333;
  text-align: center;

  h1 {
    line-height: 80px;
    font-weight: bold;
    font-size: 20px;
    margin-top: 100px;
    margin-right: -50px;
  }
}
.form {
  width: 400px;
  margin: 0 auto;
  /deep/ .el-input__inner {
    background-color: #f2f4fa;
  }
  .btnCode {
    width: 112px;
  }
}
.sendCode {
  display: flex;
  justify-content: space-between;
  .code {
    width: 60%;
  }
}
/deep/ .el-form-item {
  margin-left: -50px;
}
</style>